<template>
    <div class="common-layout">
        <el-container>
            <el-aside width="240px">
                <div class="headline">
                <img src="http://xawn.f3322.net:8002/distremote/static/img/logo.png" alt="">
                <div>赤兔养车</div>
            </div>
                <el-col :span="12">
                    <el-menu active-text-color="#ffd04b" background-color="#383e46" class="el-menu-vertical-demo"
                        default-active="2" text-color="#fff" router @open="handleOpen" @close="handleClose">
                        <el-menu-item index="/system/home">
                            <i class="iconfont Myicon-mail" style="margin: 0 10px 0 5px;"></i>
                            系统主页
                        </el-menu-item>
                        <template v-for="item in state.tableData" :key="item.path">
                            <el-menu-item v-if="!item.children" :index="item.path">{{ item.title }}</el-menu-item>
                            <el-sub-menu v-else :index="item.path">
                                <template #title>
                                    <el-icon>
                                        <i style="display: inline-block;" class="iconfont"
                                            :class="`Myicon-${item.icon}`"></i>
                                    </el-icon>
                                    <span>{{ item.title }}</span>
                                </template>
                                <el-menu-item v-for="child in item.children" :key="child.path" :index="child.path">{{
                                child.title }}</el-menu-item>
                            </el-sub-menu>
                        </template>


                    </el-menu>
                </el-col>
            </el-aside>
            <el-container>
                <el-header>
                    <el-dropdown @command="handleCommand">
                        <span class="el-dropdown-link">
                            <div class="user-icon">
                                <el-avatar
                                    :src="`http://xawn.f3322.net:8002/distremote/static/avatar/${userInfo.photoPath}`" />
                                <span>{{state.data1.username}}</span>
                            </div>
                            <el-icon class="el-icon--right">
                            </el-icon>
                        </span>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item command="a">个人中心</el-dropdown-item>
                                <el-dropdown-item command="b">密码修改</el-dropdown-item>
                                <el-dropdown-item divided command="c">系统定制</el-dropdown-item>
                                <el-dropdown-item divided command="d">退出登录</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>

                </el-header>
                <el-main>
                    <el-card class="box-card">
                        <router-view />
                    </el-card>
                </el-main>
                <el-footer>
                    <p class="footer">Copyright © 2022 赤兔养车 保留所有权利。</p>
                </el-footer>
            </el-container>
        </el-container>
    </div>

    <el-dialog v-model="dialogFormVisible" title="修改密码">
        <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules">
            <el-form-item label="旧密码：" :label-width="formLabelWidth" prop="oldpass">
                <el-input v-model="ruleForm.oldpass" type="password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="新密码：" :label-width="formLabelWidth" prop="pass">
                <el-input v-model="ruleForm.pass" type="password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="确认密码：" :label-width="formLabelWidth" prop="checkPass">
                <el-input v-model="ruleForm.checkPass" type="password" autocomplete="off" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="realGo()">确认</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { getMenuApi } from '../apis/menu'
import { onMounted, reactive, ref, watch } from 'vue'
import { router } from '../configs/router';
import { ElMessage } from 'element-plus';
import type { FormInstance } from 'element-plus'
import { checkPassApi, changePassApi } from '../apis/user'
import { useInfoStore } from '../store';
const ruleFormRef = ref<FormInstance>()

const form = reactive({
    name: '',
    region: '',
    date1: '',
    date2: '',
    delivery: false,
    type: [],
    resource: '',
    desc: '',
})

const userInfo = useInfoStore()

const state = reactive({
    data1: JSON.parse(localStorage.getItem('user') as any),
    tableData: [] as any,
    numData: {},
    check: ''
});

const handleOpen = (key: string, keyPath: string[]) => {
    console.log(key, keyPath)
}
const handleClose = (key: string, keyPath: string[]) => {
    console.log(key, keyPath)
}
const visible = ref(false)
const formLabelWidth = '140px'
const dialogFormVisible = ref(false)
async function getMenu() {
    // const username = localStorage.user.username
    const res = await getMenuApi();
    console.log(res.rows.children);
    state.tableData = res.rows.children

}

const checkOldPadd = (rule: any, value: any, callback: any) => {
    console.log(rule, value, callback);
    if (value === '') {
        callback(new Error('请输入旧密码'))
    } else {
        checkPass()
        setTimeout(() => {
            if (state.check) {
                callback()
            } else {
                callback(new Error('旧密码不正确'))
            }
        }, 500);
    }
}


const validatePass = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入密码'))
    } else {
        if (ruleForm.checkPass !== '') {
            if (!ruleFormRef.value) return
            ruleFormRef.value.validateField('checkPass', () => null)
        }
        callback()
    }
}
const validatePass2 = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请再次输入密码'))
    } else if (value !== ruleForm.pass) {
        callback(new Error("两次密码不一致"))
    } else {
        callback()
    }
}

const ruleForm = reactive({
    pass: '',
    checkPass: '',
    oldpass: '',
})

const rules = reactive({
    pass: [{ validator: validatePass, trigger: 'blur' }],
    checkPass: [{ validator: validatePass2, trigger: 'blur' }],
    oldpass: [{ validator: checkOldPadd, trigger: 'blur' }],
})

const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            console.log('submit!')
        } else {
            console.log('error submit!')
            return false
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

async function checkPass() {
    const a = `password=${ruleForm.oldpass}&username=${state.data1.username}`
    console.log(a);

    const res = await checkPassApi(a)
    console.log(res);
    state.check = res

}

async function changePass() {
    const a = `password=${ruleForm.checkPass}&username=${state.data1.username}`
    const res = await changePassApi(a)
    console.log(res);
    if (res == "") {
        ElMessage.success("密码修改成功，即将重新登录")
        setTimeout(() => {
            localStorage.clear()
            router.push("/login");
        }, 2000);
    }

}
onMounted(() => {
    getMenu();
});
const handleCommand = (command: string | number | object) => {
    console.log(command);

    switch (command) {
        case "a":
            router.push("/system/profile");
            break;
        case "b":
            dialogFormVisible.value = true
            break;
        case "c":
            ElMessage("建设中")
            break;
        case "d":
            localStorage.clear()
            router.push("/login");
            break;

    }
}
function realGo() {
    dialogFormVisible.value = false
    changePass()

}
</script>

<style scoped lang="less">
.box-card {
    width: 99%;
    height: 80vh;
}

.common-layout {
    height: 100vh;
    overflow: hidden;

    .headline {
    width: 100%;
    margin: 20px auto;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 20px;
    font-weight: bold;
    color: white;

    img {
        width: 20%;
        // height: 100%;
        margin: 20px;
    }
}
}

.el-header {
    background-color: #fff;
    padding: 0 12px 0 0;
    -webkit-box-shadow: 0 1px 4px rgba(0, 21, 41, .08);
    box-shadow: 0 1px 4px rgba(0, 21, 41, .08);
}

.el-aside {
    background-color: #383e46;
    height: 100vh;
    max-height: 100%;
}

.el-main {
    background-color: #f0f2f5;
}

.el-footer {
    background-color: #f0f2f5;
}

.el-col-12 {
    min-width: 100%;
}

.el-menu {
    width: 95%;
    height: 100%;
    border: 0;
    overflow-y: none;
    overflow-x: none;
}

.top-icon {
    width: 80%;
    margin: 20px 20px;
}

.user-icon {
    // width: 100px;
    height: 100%;
    // background-color: blanchedalmond;
    display: flex;
    align-items: center;
    float: right;

    span {
        margin-left: 5px;
        margin-right: 10px;
    }
}

.footer {
    width: 20%;
    height: 100%;
    font-size: 12px;
    color: #555;
    margin: 20px auto;
}

.el-col {
    height: 80vh;
    overflow-y: auto
}

.el-dropdown {
    height: 100%;
    float: right;
}

.el-aside::-webkit-scrollbar {
      display: none;
   }
</style>